import datetime
import copy
import numpy as np
import pandas as pd
import Core.Gadget as Gadget
from SystematicFactors.General import *

#
def Run_DDM(database, datetime1=None, datetime2=None):
    #
    df_ROE = Load_Systematic_Factor(database, "ROE_Average_TotalA")
    df_ROE["Avg"] = df_ROE["ROE_Average_TotalA"].rolling(window=3).mean()
    # print(df_ROE.head())
    print(df_ROE.tail())
    #
    df_PMI = Load_Systematic_Factor(database, "PMI")
    df_PMI["Avg"] = df_PMI["PMI"].rolling(window=12).mean()
    print(df_PMI.tail())
    #
    df_Industry = Load_Systematic_Factor(database, "Industrial_Value_Added_YoY")
    df_Industry["Avg"] = df_Industry["Industrial_Value_Added_YoY"].rolling(window=12).mean()
    print(df_Industry.tail())
    #
    df_Shibor = Load_Systematic_Factor(database, "Shibor_3M")
    df_Shibor["Avg"] = df_Shibor["Shibor_3M"].rolling(window=20*6).mean()
    print(df_Shibor.tail())
    #
    df_CreditSpread = Load_Systematic_Factor(database, "CorpBond_AAP_YTM_5Y")
    df_CreditSpread["Avg"] = df_CreditSpread["CorpBond_AAP_YTM_5Y"].rolling(window=20*6).mean()
    print(df_CreditSpread.tail())
    #
    df_CPI = Load_Systematic_Factor(database, "CPI_YoY")
    df_CPI["Avg"] = df_CPI["CPI_YoY"].rolling(window=12).mean()
    print(df_CPI.tail())

    #
    data = []
    datetimes = Gadget.generate_begin_date_of_month_list(datetime1, datetime2)
    for dt in datetimes:
        dt = dt.date()
        print(dt)
        roe_trend = 0
        pmi_trend = 0
        industry_trend = 0
        shibor_trend = 0
        cpi_trend = 0
        tbond10y_trend = 0
        credit_spread_trend = 0

        # ROE
        df_ROE_tmp = df_ROE[df_ROE["date"] <= dt]
        if len(df_ROE_tmp) == 0:
            continue

        print(df_ROE_tmp.tail())
        latest = df_ROE_tmp.iloc[-1]
        if latest["ROE_Average_TotalA"] > latest["Avg"]:
            roe_trend = 1
        else:
            roe_trend = -1

        # PMI
        print(df_PMI.tail())
        df_PMI_tmp = df_PMI[df_PMI["date"] <= dt]
        print(df_PMI_tmp.tail())
        latest = df_PMI_tmp.iloc[-1]
        if latest["PMI"] > latest["Avg"]:
            pmi_trend = 1
        else:
            pmi_trend = -1

        # Industry
        df_Industry_tmp = df_Industry[df_Industry["date"] <= dt]
        latest = df_Industry_tmp.iloc[-1]
        if latest["Industrial_Value_Added_YoY"] > latest["Avg"]:
            industry_trend = 1
        else:
            industry_trend = -1

        # Shibor
        df_Shibor_tmp = df_Shibor[df_Shibor["date"] <= dt]
        latest = df_Shibor_tmp.iloc[-1]
        if latest["Shibor_3M"] > latest["Avg"]:
            shibor_trend = 1
        else:
            shibor_trend = -1

        # Credit Spread
        df_CreditSpread_tmp = df_CreditSpread[df_CreditSpread["date"] <= dt]
        latest = df_CreditSpread_tmp.iloc[-1]
        if latest["CorpBond_AAP_YTM_5Y"] > latest["Avg"]:
            credit_spread_trend = 1
        else:
            credit_spread_trend = -1

        # CPI
        df_CPI_tmp = df_CPI[df_CPI["date"] <= dt]
        latest = df_CPI_tmp.iloc[-1]
        if latest["CPI_YoY"] > latest["Avg"]:
            cpi_trend = 1
        else:
            cpi_trend = -1

        # 确认周期
        cashflow_trend = roe_trend + pmi_trend + industry_trend
        discount_trend = shibor_trend + cpi_trend + credit_spread_trend
        print(cashflow_trend, discount_trend)
        #
        ddm_period = 0
        if cashflow_trend > 0 and discount_trend > 0:
            ddm_period = 1
        elif cashflow_trend > 0 and discount_trend < 0:
            ddm_period = 2
        elif cashflow_trend < 0 and discount_trend > 0:
            ddm_period = 3
        elif cashflow_trend < 0 and discount_trend < 0:
            ddm_period = 4
        #
        data.append([dt, dt, ddm_period])
        a = 0
    #
    df_factor = pd.DataFrame(data, columns=["ReportDate", "ReleaseDate", "DDM_Cycle"])
    print(df_factor)
    Save_Systematic_Factor_To_Database(database, df_factor, save_name='DDM_Cycle')


if __name__ == '__main__':
    #
    from Core.Config import *
    pathfilename = os.getcwd() + "\..\Config\config2.json"
    config = Config(pathfilename)
    database = config.DataBase("JDMySQL")
    realtime = config.RealTime()
    #
    datetime1 = datetime.datetime(2010, 5, 1)
    datetime2 = datetime.datetime(2020, 5, 11)
    #
    Run_DDM(database, datetime1, datetime2)